const express = require('express')
const models = require('../models')
const router = express.Router()
const Op = models.Sequelize.Op
const { success, error } = require('../utils/message')

// 搜索商品
router.get('/', async function (req, res, next) {
    const where = {}

    // 模糊查询名称
    if (req.query.name) {
        where.name = {
            [Op.like]: '%' + req.query.name + '%'
        }
    }

    const products = await models.Product.findAll({
        order: [
            ['id', 'DESC']
        ],
        where: where,
    })

    success(res, '查询成功', { products })
})

// 查询单条商品
router.get('/:id', async function (req, res, next) {
    const product = await models.Product.findByPk(req.params.id)
    if (!product) {
        return error(res, '当前商品不存在')
    }

    const recommends = await models.Product.findAll({
        where: {
            recommend: true,
            onsale: true
        },
        order: [
            ['id', 'DESC']
        ]
    })

    success(res, '查询成功', { product, recommends })
})

module.exports = router
